package cn.tedu.basic;
//测试多线程，售票案例
public class Test_Thread {
    public static void main(String[] args) {
        Tickets t =new Tickets();//创建线程
        Tickets t1 =new Tickets();
        Tickets t2 =new Tickets();
        Tickets t3 =new Tickets();
        t.start();//启动线程
        t1.start();
        t2.start();
        t3.start();
        Ticket tic =new Ticket();
        Thread th =new Thread(tic);
        Ticket tic1 =new Ticket();
        Ticket tic2 =new Ticket();
        tic.start();
        tic1.start();
        tic2.start();
        th.start();

    }
}
class Tickets extends Thread {
    static int sum = 100;//如果共享资源是静态的，锁对象是固定的：类名.class;

    //普通方法的锁对象默认分配this，静态方法的锁对象默认为类名.class;
    @Override
    public void run() {//锁方法没有效果
        while (true) {
            synchronized (Thread.class) {//同步代码块--操作共享数据的位置，实现同步，排队安全
                if (sum > 0) {
                    //问题1，重卖
                    //问题2,超卖
                    //加同步锁可以解决--底层有监视器
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(super.getName() + "--" + sum--);
                } else {
                    break;
                }
            }
        }
    }
}
class Ticket extends Thread{
   static int sum =100;
    @Override
    public void run() {
        while(true){
            synchronized(Thread.class) {
                if (sum > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "==" + sum--);
                } else {
                    break;
                }
            }
        }
    }
}